<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="null">
    <meta name="keyword" content="null">
    <meta name="theme-color" content="#600090">
    <meta name="msapplication-navbutton-color" content="#600090">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="#600090">
    <link rel="shortcut icon" href="/assets/favicon.ico">
    <link rel="alternate" type="application/atom+xml" title="张小阳" href="/atom.xml">
    <link rel="stylesheet" href="https://cdn.bootcss.com/animate.css/3.5.2/animate.css">
    <link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.css">
    <title>
        
        定心好好学之CSS盒子模型｜MillZhang&#39;s blog
        
    </title>

    <link rel="canonical" href="http://millzhang.github.io/2017/08/10/2017-original/1.定心好好学-CSS盒模型/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/blog-style.css">

    <!-- Pygments Github CSS -->
    <link rel="stylesheet" href="/css/syntax.css">
</head>

<!-- hack iOS CSS :active style -->
<body ontouchstart="" class="animated fadeIn">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top " id="nav-top" data-ispost = "true" data-istags="false
" data-ishome = "false" >
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand animated pulse" href="/">
                <span class="brand-logo">
                    MillZhang
                </span>
            </a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <!-- /.navbar-collapse -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/"><i class="fa fa-home"></i>主页</a>
                    </li>
                   <li>
                        <a href="/tags"><i class="fa fa-tags"></i>归档</a>
                    </li>
                    <li>
                        <a href="/about"><i class="fa fa-user"></i>关于</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
//    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>

<!-- Main Content -->

<!--only post-->

<header class="intro-header">
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <div class="post-heading">
                    <h1>定心好好学之CSS盒子模型</h1>
                    
                    <span class="meta">
                         作者 MillZhang
                        <span>
                          日期 2017-08-10
                         </span>
                    </span>
                    <div class="tags text-center">
                        
                        <a class="tag" href="/tags/#css"
                           title="css">css</a>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="post-title-haojen">
        <span>
            定心好好学之CSS盒子模型
        </span>
    </div>
    <div class="post-header-image">
        
            <img src="http://oritfw5nq.bkt.clouddn.com/wall-303.jpg?imageView2/0/format/jpg/interlace/1/q/85|watermark/2/text/QnkgTWlsbHpoYW5n/font/5b6u6L2v6ZuF6buR/fontsize/480/fill/I0ZERkRGRA==/dissolve/56/gravity/SouthEast/dx/10/dy/10|imageslim">
         
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">
            <!-- Post Container -->
            <div class="col-lg-8 col-lg-offset-1 col-sm-9 post-container">
                <h3 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h3><p>盒子模型是css最核心的内容了,理解盒子模型可以更好的对页面进行排版布局.<br>盒子模型又称框模型(Box Model),它是由四要素组成,分别是:</p>
<ul>
<li>元素内容(content)</li>
<li>内边距(padding)</li>
<li>边框(border)</li>
<li>外边距(margin)-透明</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//外盒尺寸计算（元素空间尺寸)</span></div><div class="line">Element空间高度 = content height + padding + border + margin</div><div class="line">Element 空间宽度 = content width + padding + border + margin</div><div class="line"><span class="comment">//内盒尺寸计算（元素大小）</span></div><div class="line">Element Height = content height + padding + border （Height为内容高度）</div><div class="line">Element Width = content width + padding + border</div></pre></td></tr></table></figure>
<p>一个标准的盒子模型的示意图:<br><img src="http://images2015.cnblogs.com/blog/793040/201511/793040-20151130140140858-2462296.jpg" alt="标准盒子模型"></p>
<p>下面我们用一组代码来演示不同的情况,如下图的盒模型:<br><img src="http://oritfw5nq.bkt.clouddn.com/20170810134534.png" alt="演示demo"></p>
<p>关于元素宽度获取的几种方式,及不同点:</p>
<ul>
<li><code>clientWidth</code>:包括元素宽度和padding,不含border的宽度值</li>
<li><code>offsetWidth</code>: dom元素实际宽度包括border和padding</li>
<li><code>scrollWidth</code>:对于无滚动元素来讲,同clientWidth,但如果内容出现滚动条,则包括滚动的宽度,也就是说scrollWidth的最小值是clientWidth,其中随内容的宽度而变</li>
<li><code>$element.width()</code>:jquery元素的宽度,单指元素的宽度</li>
</ul>
<blockquote>
<p><a href="http://jsrun.net/StYKp" target="_blank" rel="external">代码</a></p>
</blockquote>
<h3 id="盒模型的叠加"><a href="#盒模型的叠加" class="headerlink" title="盒模型的叠加"></a>盒模型的叠加</h3><p>两个上下相邻的盒模型,它们的外边距即彼此的<code>margin-bottom</code>和<code>margin-top</code>会合并,合并准则以外边距值较大的为彼此的实际外间距.</p>
<p>但是上述只针对在普通文档流中的垂直块元素,而行内元素,浮动框或者是绝对定位的元素,它们的外边距不会发生合并.</p>
<blockquote>
<p><a href="http://jsrun.net/knYKp" target="_blank" rel="external">举个栗子</a></p>
</blockquote>
<h3 id="不得不说IE的怪异盒模型"><a href="#不得不说IE的怪异盒模型" class="headerlink" title="不得不说IE的怪异盒模型"></a>不得不说IE的怪异盒模型</h3><p><img src="http://img.blog.csdn.net/20160429135409319" alt="IE盒子模型"></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/*外盒尺寸计算（元素空间尺寸）*/</span></div><div class="line"> Element空间宽度 = content Width + margin (Width包含了元素内容宽度、边框宽度、内距宽度)</div><div class="line"> <span class="comment">/*内盒尺寸计算（元素大小）*/</span></div><div class="line"> Element Width = content Width(Width包含了元素内容宽度、边框宽度、内距宽度)</div></pre></td></tr></table></figure>
<p><strong>what?</strong><br>乍一看跟标准盒模型好像没区别.但是仔细看,结合上图,怪异盒模型元素的宽度就包含了元素内容,border和padding的宽度.还不明白?</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">.box&#123;</div><div class="line">  width:200px;</div><div class="line">  height:300px;</div><div class="line">  background:#bc223d;</div><div class="line">  text-align:center;</div><div class="line">  color:#fff;</div><div class="line">  margin:20px;</div><div class="line">  padding:20px;</div><div class="line">  border:3px solid #aaabbb;</div><div class="line">  overflow-x:auto;</div><div class="line">  box-sizing:border-box;//可讲盒模型修改为怪异模型</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//怪异模型下元素宽度包括了内容的宽度,padding的宽度和border的宽度</span></div><div class="line">$(<span class="string">'.box'</span>).width();<span class="comment">//=200-20*2-3*2=154px</span></div></pre></td></tr></table></figure>
<blockquote>
<p><a href="http://jsrun.net/fnYKp" target="_blank" rel="external">代码</a></p>
</blockquote>
<h3 id="box-sizing"><a href="#box-sizing" class="headerlink" title="box-sizing"></a>box-sizing</h3><p>理解并掌握上述的两种盒模型,那么<code>box-sizing</code>这个属性相对来说更好理清了,它很好的实现了这两种模型间的互相切换,<code>box-sizing</code>有如下的属性:</p>
<ul>
<li><code>content-box</code>: 让元素维持标准盒模型,即:<code>Element Width/Height = border+padding+content width/height</code></li>
<li><code>border-box</code>: 让元素的宽度/高度等于元素内容的宽度/高度,换言之:此处的内容宽度/高度=width/height-border-padding;</li>
<li><code>inherit</code>:继承父元素<code>box-sizing</code>的属性值</li>
</ul>
<p>继续上代码,直观展现下这两种模型:</p>
<blockquote>
<p><a href="http://jsrun.net/vnYKp" target="_blank" rel="external">点击看代码</a></p>
</blockquote>
<h4 id="浏览器兼容性"><a href="#浏览器兼容性" class="headerlink" title="浏览器兼容性"></a>浏览器兼容性</h4><p>现代浏览器基本支持,IE8及以上版本支持该属性，Firefox 需要加上浏览器厂商前缀<code>-moz-</code>，对于低版本的IOS和Android浏览器也需要加上<code>-webkit-</code></p>
<p><code>boxder-box</code>更直接,更利于开发,所以有了如下的代码:</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">*, *<span class="selector-pseudo">:before</span>, *<span class="selector-pseudo">:after</span> &#123;</div><div class="line">　　<span class="attribute">-moz-box-sizing</span>: border-box;</div><div class="line">　　<span class="attribute">-webkit-box-sizing</span>: border-box;</div><div class="line">　　<span class="attribute">box-sizing</span>: border-box;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="盒模型的应用-画三角"><a href="#盒模型的应用-画三角" class="headerlink" title="盒模型的应用,画三角"></a>盒模型的应用,画三角</h3><figure class="highlight css"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="selector-class">.triangle</span> &#123;</div><div class="line">  <span class="attribute">width</span>:<span class="number">0</span>;</div><div class="line">  <span class="attribute">height</span>:<span class="number">0</span>;</div><div class="line">  <span class="attribute">border</span>:<span class="number">100px</span> solid transparent;</div><div class="line">  <span class="attribute">border-top</span>:<span class="number">100px</span> solid <span class="number">#bc223d</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p><a href="http://jsrun.net/anYKp" target="_blank" rel="external">代码</a></p>
</blockquote>

                <hr>
                <ul class="pager">
                    
                    <li class="previous">
                        <a href="/2017/08/17/2017-original/2.定心好好学-flex布局/" data-toggle="tooltip" data-placement="top"
                           title="定心好好学之flex弹性布局">&larr; 上一页</a>
                    </li>
                    
                    
                    <li class="next">
                        <a href="/2017/08/09/2017-note/29.nodejs开发指南/" data-toggle="tooltip" data-placement="top"
                           title="nodejs开发指南">下一页 &rarr;</a>
                    </li>
                    
                </ul>
                <div class="comment">
                    <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
                </div>
            </div>
            <div class="hidden-xs col-sm-3 toc-col">
                <div class="toc-wrap">
                    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#概念"><span class="toc-text">概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#盒模型的叠加"><span class="toc-text">盒模型的叠加</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#不得不说IE的怪异盒模型"><span class="toc-text">不得不说IE的怪异盒模型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#box-sizing"><span class="toc-text">box-sizing</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#浏览器兼容性"><span class="toc-text">浏览器兼容性</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#盒模型的应用-画三角"><span class="toc-text">盒模型的应用,画三角</span></a></li></ol>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Sidebar Container -->

            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                

                <!-- Friends Blog -->
                
            </div>
        </div>

    </div>
</article>
<!-- 网易云音乐-->

<iframe class="cloud-music" frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 
    src="//music.163.com/outchain/player?type=2&amp;id=18803411&amp;auto=0&amp;height=66">
</iframe>
<!-- 网易云跟帖-->
<script src="https://img1.cache.netease.com/f2e/tie/yun/sdk/loader.js"></script>
<script>
var cloudTieConfig = {
  url: document.location.href, 
  sourceId: "",
  productKey: "40a8ee22b6084862a8907e6902e525fa",
  target: "cloud-tie-wrapper"
};
var yunManualLoad = true;
Tie.loader("aHR0cHM6Ly9hcGkuZ2VudGllLjE2My5jb20vcGMvbGl2ZXNjcmlwdC5odG1s", true);
</script>

<!-- Footer -->
<!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <p class="copyright text-muted">
                    Copyright &copy; MillZhang 2017
                    <br>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/blog.js"></script>

<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("http://oritfw5nq.bkt.clouddn.com/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>



<!--wechat title img-->
<img class="wechat-title-img" src="http://oritfw5nq.bkt.clouddn.com/avatar.jpg?imageslim">
<a id="backtop" class="border-bottom" href="javascript:;">回顶部</a>
<script type="application/javascript">
var docOuter = document.body.scrollTop ? document.body : document.documentElement;
var backToTop = function(rate) {
  var doc = document.body.scrollTop ? document.body : document.documentElement;
  var scrollTop = doc.scrollTop;
  var top = function() {
    scrollTop = scrollTop + (0 - scrollTop) / (rate || 2);
    if (scrollTop < 1) {
      doc.scrollTop = 0;
      return;
    }
    doc.scrollTop = scrollTop;
    // 动画gogogo!
    requestAnimationFrame(top);
  };
  top();
};
var topBtn = document.getElementById('backtop'),
    docTop = docOuter.scrollTop;
if(docTop>=300){
  topBtn.style.opacity = 1;
}

topBtn.onclick = function() {
  backToTop(12)
}
window.onscroll = function(e) {
  var doc = document.body.scrollTop ? document.body : document.documentElement;
  var scrollTop = doc.scrollTop;
  if (scrollTop >= 300) {
    topBtn.style.opacity = 1;
  } else {
    topBtn.style.opacity = 0;
  }
}
</script>
</body>

</html>
